package com.cg.controller;

import com.cg.entity.Category;
import com.cg.entity.Events;
import com.cg.entity.User;
import com.cg.exception.UserException;
import com.cg.service.CategoryService;
import com.cg.service.EventsService;
import com.cg.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/user")
public class UserController {
  @Autowired
  private UserService userService;
  @Autowired
  private EventsService eventsService;
  @Autowired
  private CategoryService categoryService;

  //用户退出
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        // 清除session中的用户信息
        request.getSession().invalidate();
        return "/login"; // 退出后重定向到登录页面
    }

    @RequestMapping(value = "/home")
    public String home(HttpServletRequest request, Model model){
        User user = (User) request.getSession().getAttribute("user");
        if(user!=null){
            return "home";
        }else {
            model.addAttribute("MainError", "请先登录");
            return "login";
        }

    }

    //主页面
    @RequestMapping("/Main")
    public String Main(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        Integer userId = user.getUserId();

        List<Events> eventsList = eventsService.eventsList(userId, null, "", null, null);
        ObjectMapper objectMapper = new ObjectMapper();
        String eventsListJson = "";
        try {
            eventsListJson = objectMapper.writeValueAsString(eventsList);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        request.setAttribute("eventsListJson", eventsListJson);
        List<Category> categoryList = categoryService.categoryList(userId, "");
        String categoryListJson = "";
        try {
            categoryListJson = objectMapper.writeValueAsString(categoryList);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        request.setAttribute("categoryListJson", categoryListJson);
        return "Main";
    }

//登录
  @RequestMapping(value = "/login")
   public String login(){
    return "login";
  }
    @RequestMapping(value = "/doLogin", method = RequestMethod.POST)
    public String login(HttpServletRequest request, Model model) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if(username.equals("")  || password.equals("")){
            model.addAttribute("loginError", "请输入账号和密码");
            return "/login"; // 假设登录页面的路径是 /user/login
        }

        User user = userService.login(username, password);
        if (user != null) {
            request.getSession().setAttribute("user", user);
            return "/home";
        } else {
            model.addAttribute("loginError", "用户名或密码错误");
            return "/login"; // 假设登录页面的路径是 /user/login
        }
    }

    //注册
    @RequestMapping(value = "/doRegister", method = RequestMethod.POST)
    public String doRegister(HttpServletRequest request, User user, HttpServletResponse response,Model model) {
        // 检查用户名或邮箱是否已经存在
        User user1 = userService.findByUsername(user.getUsername());
        if (user1 != null) {
            // 如果用户名或邮箱已存在，
            model.addAttribute("registerError", "用户名已存在");
            return "/login";
        }
        // 尝试保存新用户到数据库
        try {
            userService.addUser(user);
            model.addAttribute("registerSuccess", "注册成功，请登录");
        } catch (Exception e) {
            request.getSession().setAttribute("error", "注册失败：" + e.getMessage());
        }
      return "/login"; // 注册成功后重定向到登录页面
    }

}
